/**
 * 
 */
package com.csc.bankingsystem.core.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csc.bankingsystem.core.dao.HistoryRecordDAO;
import com.csc.bankingsystem.core.entity.HistoryRecord;
import com.csc.bankingsystem.core.entity.UserInfo;
import com.csc.bankingsystem.core.enumeration.HistoryRecordActionEnum;
import com.csc.bankingsystem.core.service.HistoryRecordService;
import com.csc.bankingsystem.core.service.TokenRecordService;
import com.csc.bankingsystem.core.service.UserInfoService;


/**
 * Implement all service operation of HistoryRecordService
 * @author angelkid
 *
 */
@Service("historyRecordService")
@Transactional
public class HistoryRecordServiceImpl implements HistoryRecordService {
	@Autowired
	private HistoryRecordDAO historyRecordDAO;
	
	@Autowired
	private TokenRecordService tokenRecordService;
	
	@Autowired
	private UserInfoService userInfoService;

	public HistoryRecord find(long id) {
		return historyRecordDAO.find(id);
	}

	public List<HistoryRecord> findAll() {
		return historyRecordDAO.findAll();
	}

	public Long countAll() {
		return historyRecordDAO.countAll();
	}

	public Long save(HistoryRecord historyRecord){
		return historyRecordDAO.save(historyRecord);
	}

	public void update(HistoryRecord historyRecord){
		historyRecordDAO.update(historyRecord);
	}

	public void delete(HistoryRecord historyRecord) {
		historyRecordDAO.delete(historyRecord);
	}
	
	public void saveLoginSuccessByUserInfoObject(UserInfo userInfo) {
		Date now = new Date();
		userInfoService.updateByUserObject(userInfo);
		
		HistoryRecord historyRecord = new HistoryRecord();
		historyRecord.setAction(HistoryRecordActionEnum.LOGIN);
		historyRecord.setCreateDate(now);
		historyRecord.setCreateUser(userInfo.getLoginId());
		historyRecord.setStartTime(now);
		historyRecord.setUserInfo(userInfo);
		historyRecordDAO.save(historyRecord);
	}
	
	public void saveLogoutSuccessByLoginId(String loginId) {
		UserInfo userInfo =userInfoService.getUserInfoByLoginId(loginId);
		Date now = new Date();
		
		tokenRecordService.deleteTokenForLoginId(userInfo);
		HistoryRecord historyRecord = new HistoryRecord();
		historyRecord.setAction(HistoryRecordActionEnum.LOGOUT);
		historyRecord.setCreateDate(now);
		historyRecord.setCreateUser(userInfo.getLoginId());
		historyRecord.setStartTime(now);
		historyRecord.setUserInfo(userInfo);
		historyRecordDAO.save(historyRecord);
	}
}
